var Navbar = function(wrapper, leftIcon, rightIcon) {
  this.wrapper = wrapper;
  this.leftIcon = leftIcon;
  this.rightIcon = rightIcon;
  this.list = $(wrapper.children('ul').children('li'));
  this.listWidth = this.setListWidth();
  this.wrapperWidth = this.setWrapperWidth();
  this.iconWidth = 14;

  $(wrapper.children('ul')).css({"min-width": this.listWidth});

};
// 获取导航条中从1到n的项目宽度
Navbar.prototype.setItemsWidth = function(x, y) {
  if (x > y || y > this.list.length || x < 1) { return 0; }
  var itemsWidth = 0;
  for (var i=x-1; i<y; i++) {
    itemsWidth += $(this.list[i]).outerWidth();
  }
  return itemsWidth;
};

Navbar.prototype.setListWidth = function() {
  var itemsWidth = 0;
  this.list.each( function() {
    itemsWidth += $(this).outerWidth();
  });
  return itemsWidth;
};

Navbar.prototype.setWrapperWidth = function() {
  return this.wrapper.outerWidth();
};

Navbar.prototype.getFirstPosi = function() {
  return $(this.list[0]).offset().left - this.iconWidth;
};

Navbar.prototype.getLastPosi = function() {
  var lastNo = this.list.length - 1;
  return $(this.list[lastNo]).offset().left + $(this.list[lastNo]).outerWidth() - this.iconWidth;
};

Navbar.prototype.reAdjust = function() {
  $('#test-output').text("left: " + this.getLastPosi());
  if (this.getFirstPosi() < 0) {
    $(this.leftIcon).show("fast");
  } else {
    $(this.leftIcon).hide("fast");
  }    

  if (this.getLastPosi() > this.wrapperWidth) {
    $(this.rightIcon).show("fast");
  } else {
    $(this.rightIcon).hide("fast");
  }
};

$(document).ready( function() {
  var nb = new Navbar($('.horizontal-scroller.body'), $('.horizontal-scroller.icon-left i'), $('.horizontal-scroller.icon-right i'));
  nb.reAdjust();
  $(nb.wrapper).scroll(function () {
    nb.reAdjust();
  });
});


